import { FastifyReply, FastifyRequest } from 'fastify';
import { Controller, GET, POST } from 'fastify-decorators';
import { z } from "zod";
import { app } from '..';
import paypalService from '../service/paypal.service';
import dayjs from 'dayjs';


@Controller({ route: '/payment' })
export default class PaypalController {
    orderCaptureSchema = z.object({
        orderId: z.string(),
        subscriptionPlanId: z.number()
    });

    @GET('/token')
    async getTokenInfo(request: FastifyRequest, reply: FastifyReply) {
        const tokenInfo = await paypalService.getToken();
        return app.json(tokenInfo.data);
    }

    @POST('/order/create')
    async createOrder(request: FastifyRequest, reply: FastifyReply) {
        const orderInfo = await paypalService.createOrder();
        return app.json(orderInfo);
    }

    @POST('/order/capture')
    async captureOrder(request: FastifyRequest, reply: FastifyReply) {
        const { orderId, subscriptionPlanId } = this.orderCaptureSchema.parse(request.body);

        const orderInfo = await app.prisma.$transaction(async (tx) => {
            const orderInfo = await paypalService.captureOrder(orderId);
            await tx.userPayment.create({
                data: {
                    userId: +request.user.id,
                    orderId,
                    subscriptionPlanId,
                    amount: orderInfo.purchase_units[0].payments.captures[0].amount.value,
                }
            });
            const startDate = new Date();
            await tx.userSubscription.create({
                data: {
                    userId: +request.user.id,
                    subscriptionPlanId,
                    startDate,
                    endDate: dayjs(startDate).add(1, 'month').toDate(),
                }
            });
            return orderInfo;
        });

        return app.json(orderInfo);
    }
}